<template>
  <ProjectInfo
    :projectId="`${route.query.projectId}`"
    :reportType="'HHJC'"
    :sign="true"
    :sync="true"
    :syncContent="'从耗材领用同步滤膜数量信息'"
    :preview="true"
    @preview-file="onPreviewHeader"
    @on-sync-header="onSyncHeader"
    ref="projectInfoRef"
    :needSignatureCheck="true"
    @signature="handleSignature"
  />
  <ContentWrap class="chem-record-wrap">
    <div class="header-container-consumable">
      <!-- Title Centered -->
      <h2 class="centered-title-consumable">滤膜的采样前测量记录表</h2>
    </div>
    <!-- 头部信息表单 -->
    <el-form :model="form" class="chem-form" label-width="100px">
      <el-row :gutter="24" align="middle">
        <el-col :span="8">
          <el-form-item label="仪器名称">
            <el-input
              v-model="form.instrumentName"
              placeholder="双击选择"
              readonly
              @dblclick="openFacilityDialog()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="仪器型号">
            <el-input
              v-model="form.instrumentModel"
              placeholder="双击选择"
              readonly
              @dblclick="openFacilityDialog()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="仪器编号">
            <el-input
              v-model="form.instrumentNo"
              placeholder="双击选择"
              readonly
              @dblclick="openFacilityDialog()"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" align="middle">
        <el-col :span="4">
          <el-form-item label="气温(℃)">
            <el-input v-model="form.temperature" placeholder="请输入气温" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="湿度(%RH)">
            <el-input v-model="form.humidity" placeholder="请输入湿度" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="砝码标准值(g)">
            <el-input v-model="form.fmbzz" placeholder="请输入标准砝码标准值" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="砝码称量质量(g)">
            <el-input v-model="form.fmclz" placeholder="请输入标准砝码称量质量" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 表格 -->
    <el-table :data="form.table" border class="chem-table" stripe table-layout="fixed">
      <el-table-column align="center" label="序号" type="index" />
      >
      <el-table-column align="center" label="称量滤膜编号" prop="cllmbh">
        <template #default="{ row }">
          <el-input v-model="row.cllmbh" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="滤膜质量m(g)" prop="quality">
        <template #default="{ row }">
          <el-input v-model="row.quality" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark">
        <template #default="{ row }">
          <el-input v-model="row.remark" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150">
        <template #default="{ $index }">
          <el-button link size="small" @click="addRow($index)" style="margin-right: 5px">
            添加行
          </el-button>
          <el-button
            link
            type="danger"
            size="small"
            @click="deleteRow($index)"
            :disabled="form.table.length <= 1"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <el-dialog
    v-model="facilityDialogVisible"
    append-to-body
    destroy-on-close
    title="选择设备"
    width="60%"
  >
    <div class="dialog-content">
      <Facility
        :default-status="1"
        :show-selection="false"
        @selection-change="handleFacilitySelectionChange"
        @handle-facility-confirm="handleFacilityConfirm"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="facilityDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleFacilityConfirm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { ProjectApi } from '@/api/dk/project'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import Facility from '@/views/infra/facility/facility.vue'
import ProjectInfo from '@/views/project/list/ProjectInfo.vue'

const route = useRoute()
const router = useRouter()
const selectedFacility = ref<any>(null)
const loading = ref(false)
const mounting = ref(false)
const form = ref({
  temperature: '',
  humidity: '',
  projectId: route.query.projectId,
  instrumentName: '',
  instrumentModel: '',
  instrumentNo: '',
  fmbzz: '0.05000',
  fmclz: '0.05000',
  table: [
    {
      cllmbh: '',
      sampleNo: '',
      sampleVolume: '',
      quality: '',
      remark: ''
    }
  ]
})
const facilityDialogVisible = ref(false)
const projectInfoRef = ref()
// 处理签名事件
const handleSignature = () => {
  // 先进行数据校验
  if (signatureCheck()) {
    // 校验通过，显示签名弹窗
    if (projectInfoRef.value) {
      projectInfoRef.value.showSignatureDialog()
    }
  }
  // 校验不通过时，不显示弹窗，错误信息已在 signatureCheck 中提示
}
// 签名前校验：表格必填项不能为空
const signatureCheck = (): boolean => {
  const table = form.value.table || []
  if (table.length === 0) {
    ElMessage.error('表格数据不能为空')
    return false
  }
  for (let i = 0; i < table.length; i++) {
    const row = table[i] as any
    const rowIndex = i + 1
    if (!row.cllmbh || String(row.cllmbh).trim() === '') {
      ElMessage.error(`第${rowIndex}行“称量滤膜编号”不能为空`)
      return false
    }
    if (!row.quality || String(row.quality).trim() === '') {
      ElMessage.error(`第${rowIndex}行“滤膜质量m(g)”不能为空`)
      return false
    }
  }
  return true
}
const openFacilityDialog = () => {
  facilityDialogVisible.value = true
}
const handleFacilitySelectionChange = (selection: any[]) => {
  const facility = Array.isArray(selection[0]) ? selection[0][0] : selection[0]
  selectedFacility.value = facility || null
}
const handleFacilityConfirm = () => {
  console.log('确认选择设备:', JSON.stringify(selectedFacility.value))
  if (selectedFacility.value) {
    form.value.instrumentName = selectedFacility.value.name
    form.value.instrumentModel = selectedFacility.value.model
    form.value.instrumentNo = selectedFacility.value.serialNumber
    console.log('选择设备form:', JSON.stringify(form.value))
    console.log('选择设备:', JSON.stringify(selectedFacility.value))
    facilityDialogVisible.value = false
    selectedFacility.value = null
    ElMessage.success('选择设备成功')
  } else {
    ElMessage.warning('请选择设备')
  }
}
const getDefaultSampleHandoverRecord = async () => {
  const projectId = route.query.projectId as string
  const result = await ProjectApi.getDefaultBeforeSample(Number(projectId))
  form.value.table = result.table
  console.log('form.value',JSON.stringify(form.value))
}
watch(
  form,
  async (newValue, oldValue) => {
    console.log('form changed:', JSON.stringify(newValue))
    // 在这里执行你的逻辑
    await ProjectApi.updateBeforeSample(form.value)
    if (mounting.value) {
      mounting.value = false
      return
    }
    if (!loading.value) {
      ElMessage.success('修改成功')
    } else {
      ElMessage.success('同步成功')
    }
    loading.value = false
  },
  { deep: true } // 深度监听，因为 form 是嵌套对象
)

onMounted(async () => {
  mounting.value = true
  const projectId = route.query.projectId as string
  const result = await ProjectApi.getBeforeSample(Number(projectId))
  form.value = {
    ...form.value,
    ...result
  }
  // 初始化称量滤膜编号
  reorderFilterNumbers()
})

// 头部按钮事件
const onSyncHeader = async () => {
  try {
    await ElMessageBox.confirm('已有数据将被覆盖，确认是否同步？', '确认同步', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
  } catch (_) {
    return
  }
  loading.value = true
  await getDefaultSampleHandoverRecord()
}
const onPreviewHeader = () => {
  // 跳转到现场调查页面，并携带项目信息
  const { projectId, projectNo } = route.query
  router.push({
    path: '/previewFile',
    query: {
      projectId: projectId,
      projectNo: projectNo,
      operationType: 11
    }
  })
}

// 重新排序称量滤膜编号
const reorderFilterNumbers = () => {
  form.value.table.forEach((row, index) => {
    row.cllmbh = String(index + 1)
  })
}

// 添加行
const addRow = (index: number) => {
  const newRow = {
    cllmbh: '',
    sampleNo: '',
    sampleVolume: '',
    quality: '',
    remark: ''
  }
  form.value.table.splice(index + 1, 0, newRow)
  reorderFilterNumbers()
}

// 删除行
const deleteRow = (index: number) => {
  if (form.value.table.length > 1) {
    form.value.table.splice(index, 1)
    reorderFilterNumbers()
  } else {
    ElMessage.warning('至少保留一行数据')
  }
}
</script>

<style lang="scss" scoped>
.header-container-consumable {
  display: flex; // Use flex layout
  justify-content: space-between; // Space between title and button container
  align-items: center; // Vertically align items
  margin-bottom: 20px; // Add space below the header block
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e6eb;
}

.env-item {
  display: flex;
  align-items: center;
}

.centered-title-consumable {
  text-align: center; // Center the text inside this element
  flex-grow: 1; // Allow the title to take up available space
  margin: 0; // Reset default margin to correctly center
  color: #333;
  font-size: 24px;
  font-weight: bold;
}

.chem-form {
  background: none;
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;

  :deep(.el-input__inner) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  :deep(.el-form-item__label) {
    white-space: nowrap;
  }
}

.chem-btns {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

.chem-table {
  margin-top: 18px;
  --el-table-border-radius: 0 !important;
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #e5e6eb;
  box-shadow: none !important;
  border-radius: 0 !important;

  :deep(.el-table__header th) {
    background: #f7f8fa !important;
    font-weight: 600;
    font-size: 14px;
    border-radius: 0 !important;
    padding: 8px 0 !important;

    .cell {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }
  }

  // 设置表格行高
  :deep(.el-table__body td) {
    border-radius: 0 !important;

    font-size: 14px;
    padding: 0 !important;
    // 列和单元格的边距
    .cell {
      padding: 0px 0px;
    }
  }

  // 去掉输入框边框
  :deep(.el-input__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  // 针对下拉选择框的所有相关元素去掉边框
  :deep(.el-select__wrapper) {
    border: none !important;
    box-shadow: none !important;
  }
}

.input-with-unit {
  position: relative;
}

:deep(.el-input__inner) {
  text-align: center;
}

.unit-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 14px;
  pointer-events: none;
  z-index: 1;
}
</style>
